
import React, { useEffect, useState } from 'react';

/**
 * localStorage 持久化存储
 * @param {*} key 
 * @param {*} initVal 
 */


const useLocal=(key,initVal=[])=>{
    if(typeof key !=='string'){
        throw new Error('key must be a string')
    }

    let preStr;
    try{
        let localStr=localStorage.getItem(key);  // 
        if(!localStr){
            localStr=null;
        }
        preStr=JSON.parse(localStr);  // JSON

    }
    catch(err){
        console.error(err)
    }

    // 通用性
    console.log(preStr,'===');
    let [value,setValue] =useState(preStr||initVal);
    console.log(typeof value,'---');

    useEffect(()=>{
        localStorage.setItem(key,JSON.stringify(value));
    },[value])

    return [value,setValue];
}

export default useLocal;